
local alien = require 'alien'
local gtk = require 'bindings.libgtk'
local gdk = require 'bindings.libgdk'
local tostring, error, ipairs, type, assert
    = tostring, error, ipairs, type, assert
local gsub
    = string.gsub


module (...)


gtk.init(nil, nil)

function alert(message, title)
  message = gsub(tostring(message), '%%', '%%%%')
  title = gsub(tostring(title or 'Message'), '%%', '%%%%')
  local msgbox = gtk.message_dialog_new(main_window, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, title)
  gtk.message_dialog_format_secondary_text(msgbox, message)
  gtk.dialog_run(msgbox)
  gtk.widget_destroy(msgbox)
end

function confirm(message, title, default)
  message = gsub(message, '%%', '%%%%')
  if (default == nil) and (type(title) == 'boolean') then
    title, default = nil, title
  end
  title = gsub(tostring(title or 'Please confirm'), '%%', '%%%%')
  local msgbox = gtk.message_dialog_new(main_window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, title)
  gtk.message_dialog_format_secondary_text(msgbox, message)
  gtk.dialog_set_default_response(msgbox, default and gtk.RESPONSE_YES or gtk.RESPONSE_NO)
  local result = (gtk.dialog_run(msgbox) == gtk.RESPONSE_YES)
  gtk.widget_destroy(msgbox)
  return result
end

function choosefile(def)
  assert(type(def) == 'table', 'expecting options table')
  local action = def.mode or 'open'
  local message = def.message
  local button_text
  if (action == 'save') then
    action = gtk.FILE_CHOOSER_ACTION_SAVE
    message = message or "Save As"
    button_text = "Save"
  elseif (action == 'open') then
    action = gtk.FILE_CHOOSER_ACTION_OPEN
    message = message or "Open"
    button_text = "Open"
  else
    error('unknown file choice mode',2)
  end
  local chooser = gtk.file_chooser_dialog_new(message, nil, action, nil)
  gtk.dialog_add_button(chooser, button_text, gtk.RESPONSE_ACCEPT)
  gtk.dialog_add_button(chooser, "Cancel", gtk.RESPONSE_CANCEL)
  local filters = def.filters
  if filters then
    for i,filter_def in ipairs(filters) do
      local gtk_filter = gtk.file_filter_new()
      for i, pattern in ipairs(filter_def.patterns) do
        gtk.file_filter_add_pattern(gtk_filter, pattern)
      end
      gtk.file_filter_set_name(gtk_filter, filter_def.display)
      gtk.file_chooser_add_filter(chooser, gtk_filter)
    end
  end  
  local filename
  if (gtk.dialog_run(chooser) == gtk.RESPONSE_ACCEPT) then
    filename = gtk.file_chooser_get_filename_utf8(chooser)
  end
  gtk.widget_destroy(chooser)
  return filename
end
